<script setup lang="ts" name="AthleteFirstRegisterConfirm">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'

// 身份验证列表项类型
interface AuthListItem {
	img: string
	title: string
	description: string
	validateStatus: number
	unValidate: string
	validated: string
	type: 'identity' | 'face' | 'fingerprint'
	verifyKey: 'verifyIdentity' | 'verifyFace' | 'verifyFingerprint'
}

import { basicFormOptions, isYearlyConfirm, setYearlyConfirmMode } from './formConfig'
import StepNavigation from './components/StepNavigation.vue'
import CommonUpload from './components/commonUpload.vue'
import SubmitConfirmDialog from './components/SubmitConfirmDialog.vue'
import mgzPlaceholder from '@/assets/athlete/icons/mgzPlaceholder.png'
import certiPlaceholder from '@/assets/athlete/icons/certiPlaceholder.png'
import otherPlaceholder from '@/assets/athlete/icons/otherPlaceholder.png'
import idFrontPlaceholder from '@/assets/athlete/icons/idFront.png'
import idBackPlaceholder from '@/assets/athlete/icons/idBack.png'
import idValidate from '@/assets/athlete/icons/idValidate.svg'
import faceValidate from '@/assets/athlete/icons/faceIdValidate.svg'
import fingerprintValidate from '@/assets/athlete/icons/fingerprintValidate.svg'
import fileIcon from '@/assets/athlete/detail/file.png?url'
import { createAthleteApi, yearConfirmApi } from '@/api/athlete'
import { toApiModel, type AthleteViewModel } from '@/api/athlete/transformer'
import { recognizeIdCardApi } from '@/api/ocr'
import { useUserStore } from '@/store/user'
import { useDict } from '@/composables/useDict'
import { QForm } from '@meetjs/element-plus-kit'
import { SYSTEM_DICT } from '@/constants/dictKeys'
import dayjs from 'dayjs'
import { ManagementStatus } from '@/api/athlete/types'
import { re } from 'mathjs'

// Store
const userStore = useUserStore()
const curAthlete = userStore.userInfo.athlete

const { dicts } = useDict([])

const disabled = computed(() => {
	// 用户刚提交 或者 是 待年度确认 、被拒绝 才需要 返回 true，其它返回false
	return (
		isSubmit.value ||
		![ManagementStatus.toRegister, ManagementStatus.REJECTED].includes(curAthlete?.approvalStatus as ManagementStatus)
	)
})

// 运动员状态
const approvalStatus = computed(() => {
	return curAthlete?.registerStatus || 0
})

const validating = ref(false)
const submitting = ref(false)
const ocrProcessing = ref(false)
const pageLoading = ref(true) // 页面初始化加载状态

// 确认弹窗状态
const showConfirmDialog = ref(false)

// 步骤配置
const steps = ref([
	{
		title: `${isYearlyConfirm.value ? '信息核对与更细' : '信息填报'}`,
		description: `${isYearlyConfirm.value ? '确认信息' : '请填写个人基础信息'}`
	},
	{
		title: '附件上传',
		description: '上传相关证明材料'
	},
	{
		title: '身份验证',
		description: '完成身份认证'
	}
])

// 表单数据
const registerForm = ref<Partial<AthleteViewModel>>({
	registerYear: dayjs().format('YYYY')
})

// 协议确认
const agreementChecked = reactive({
	info: false,
	privacy: false
})

// 表单引用
const basicFormRef = ref()

const isFieldFilled = (value: any) => {
	if (value === null || value === undefined) return false
	if (typeof value === 'string') return value.trim() !== ''
	if (typeof value === 'number') return value > -1 // 处理0值的情况（如性别：0=男，1=女）
	if (Array.isArray(value)) return value.length > 0
	return Boolean(value)
}

const step1Complete = computed(() => {
	const step1Fields = [
		// 基本信息
		'athleteName', // 姓名
		'nation', // 民族
		'sex', // 性别
		'birthday', // 出生日期

		// 证件信息
		'idNumber', // 证件号码
		'authority', // 发证机关
		'cardExpStart', // 有效期起始时间
		'cardExpEnd', // 有效期截止时间

		// 联系信息
		'address', // 户籍地址

		// 身体信息
		'height', // 身高(cm)
		'weight', // 体重(kg)

		// 机构信息
		'registerOrgId', // 注册单位ID
		'trainOrgCascade', // 在训单位ID
		'school', // 在读学校
		'grade', // 在读年级
		'studentNumber', // 学籍卡号

		// 运动信息
		'registerProject', // 注册项目
		'coachName', // 现任教练员

		// 监护人信息
		'guardian', // 监护人
		'guardianPhone', // 监护人联系方式

		// 协议信息
		'agreementPeriod', // 协议周期
		'registerYear', // 注册年度

		// 身份证照片上传
		'identityFront', // 身份证正面照片
		'identityBack' // 身份证背面照片
	]

	return step1Fields.every(field => {
		const value = registerForm.value[field as keyof typeof registerForm.value]
		const filled = isFieldFilled(value)
		if (!filled) {
			console.log('step1Complete未填: ', field, '---', value)
		}
		return filled
	})
})

const step2Complete = computed(() => {
	const step2Fields = ['personPhoto', 'qualifications', 'otherMaterial']
	return step2Fields.every(field => {
		const value = registerForm.value[field as keyof typeof registerForm.value]
		const filled = isFieldFilled(value)
		if (!filled) {
			console.log('step2Complete未填: ', field, '---', value)
		}
		return filled
	})
})

const currentStep = computed(() => {
	if (!step1Complete.value) return 1
	if (!step2Complete.value) return 2
	return 3
})

const canSubmit = computed(() => {
	// 1. 检查协议是否勾选
	if (!agreementChecked.info || !agreementChecked.privacy) {
		return false
	}

	// 2. 检查所有必填的表单字段
	const requiredFormFields = [
		'athleteName', // 姓名
		'nation', // 民族
		'sex', // 性别
		'birthday', // 出生日期
		'idNumber', // 证件号码
		'authority', // 发证机关
		'cardExpStart', // 有效期起始时间
		'cardExpEnd', // 有效期截止时间
		'address', // 户籍地址
		'height', // 身高(cm)
		'weight', // 体重(kg)
		'registerOrgId', // 注册单位
		'trainOrgCascade', // 在训单位
		'school', // 在读学校
		'grade', // 在读年级
		'studentNumber', // 学籍卡号
		'registerProject', // 注册项目
		'coachName', // 现任教练员
		'guardian', // 监护人
		'guardianPhone', // 监护人联系方式
		'agreementPeriod' // 协议周期
	]

	// 检查必填表单字段是否都有值
	const allFormFieldsFilled = requiredFormFields.every(field => {
		const value = registerForm.value[field as keyof typeof registerForm.value]
		if (value === null || value === undefined) return false
		if (typeof value === 'string') return value.trim() !== ''
		if (Array.isArray(value)) return value.length > 0
		if (typeof value === 'number') return value > 0 || value === 0 // 包括sex字段的0值
		return Boolean(value)
	})

	if (!allFormFieldsFilled) {
		return false
	}

	// 3. 检查必填的文件上传字段
	const requiredFileFields = [
		'identityFront', // 身份证正面
		'identityBack', // 身份证背面
		'personPhoto', // 近期免冠照片
		'qualifications', // 运动员资质证书
		'otherMaterial' // 其他相关证明
	]

	const allFilesFilled = requiredFileFields.every(field => {
		const value = registerForm.value[field as keyof typeof registerForm.value]
		if (Array.isArray(value)) {
			return value.length > 0
		}
		return Boolean(value)
	})

	if (!allFilesFilled) {
		return false
	}

	// 暂时不验证身份验证三项，后续可根据需求启用
	return true
})

const authList = ref<AuthListItem[]>([
	{
		img: idValidate,
		title: '身份验证',
		description: '系统将自动验证您的身份证信息真实性',
		validateStatus: 0,
		unValidate: '开始验证',
		validated: '已验证',
		type: 'identity',
		verifyKey: 'verifyIdentity'
	},
	{
		img: faceValidate,
		title: '人脸识别',
		description: '将您的照片与身份证照片进行比对验证',
		validateStatus: 0,
		unValidate: '开始识别',
		validated: '已识别',
		type: 'face',
		verifyKey: 'verifyFace'
	},
	{
		img: fingerprintValidate,
		title: '指纹录入',
		description: '录入指纹信息，确保身份的唯一性',
		validateStatus: 0,
		unValidate: '录入指纹',
		validated: '已录入',
		type: 'fingerprint',
		verifyKey: 'verifyFingerprint'
	}
])

// 证件审核记录资料
const auditRecords = ref([
	{
		id: 1,
		title: '注册审核中',
		operator: '审核员A',
		description: '请等待审核员审核',
		time: '2024-09-09'
	}
])

// 验证处理函数
const handleVerify = async (type: 'identity' | 'face' | 'fingerprint') => {
	try {
		validating.value = true

		// 模拟验证API调用
		await new Promise(resolve => setTimeout(resolve, 1500))

		// 更新表单验证状态
		if (type === 'identity') {
			registerForm.value.verifyIdentity = 1 // 1=已验证, 0=未验证
			ElMessage.success('身份验证成功')
		} else if (type === 'face') {
			registerForm.value.verifyFace = 1 // 1=已验证, 0=未验证
			ElMessage.success('人脸识别成功')
		} else if (type === 'fingerprint') {
			registerForm.value.verifyFingerprint = 1 // 1=已验证, 0=未验证
			ElMessage.success('指纹录入成功')
		}

		// 更新 authList 中的验证状态
		const authItem = authList.value.find(item => item.type === type)
		if (authItem) {
			authItem.validateStatus = 1
		}
	} catch (error) {
		ElMessage.error('验证失败，请重试')
	} finally {
		validating.value = false
	}
}

const isSubmit = ref(false)

// 原始提交函数重命名
const doActualSubmit = async () => {
	try {
		submitting.value = true

		const apiParams = toApiModel(registerForm.value)

		// 根据是否年度确认调用不同的接口
		let res
		if (isYearlyConfirm.value) {
			// 年度确认接口
			res = await yearConfirmApi(apiParams)
		} else {
			// 首次注册接口
			res = await createAthleteApi(apiParams)
		}

		ElMessage.success(isYearlyConfirm.value ? '年度确认申请提交成功，请等待审核' : '注册申请提交成功，请等待审核')
		isSubmit.value = true
		showConfirmDialog.value = false
	} finally {
		submitting.value = false
	}
}

// 主提交函数（判断是否需要二次确认）
const handleSubmit = async () => {
	if (isYearlyConfirm.value) {
		// 年度确认时显示确认弹窗
		showConfirmDialog.value = true
	} else {
		// 首次注册直接提交
		await doActualSubmit()
	}
}

// 确认提交函数
const handleConfirmSubmit = async () => {
	await doActualSubmit()
}

// 取消提交函数
const handleCancelSubmit = () => {
	showConfirmDialog.value = false
}

/**
 * 处理身份证照片上传成功后的OCR识别
 * @param file 原始文件对象
 */
const handleIdCardOcr = async (file: File) => {
	try {
		ocrProcessing.value = true
		ElMessage.info('正在识别身份证信息...')

		console.log('开始OCR识别，文件信息:', {
			name: file.name,
			size: file.size,
			type: file.type
		})

		// 直接使用原始文件进行OCR识别
		const ocrResponse = await recognizeIdCardApi(file)

		if (ocrResponse.code === 200 && ocrResponse.data) {
			const ocrData = ocrResponse.data

			// 映射OCR结果到表单字段
			if (ocrData.realName) {
				registerForm.value.athleteName = ocrData.realName
			}

			if (ocrData.idNumber) {
				registerForm.value.idNumber = ocrData.idNumber
			}

			if (ocrData.sex) {
				// 将性别文字转换为数字：男=0，女=1（根据Gender枚举定义）
				registerForm.value.sex = ocrData.sex === '男' ? 0 : 1
			}

			if (ocrData.nation) {
				// 如果OCR返回的是民族名称，需要转换为数字ID
				// 这里先直接赋值，如果是数字则直接使用，如果是字符串则需要通过字典转换
				const nationValue = dicts[SYSTEM_DICT.NATION].value.find(item => item.label.includes(ocrData.nation))?.value || 0
				registerForm.value.nation = nationValue
			}

			if (ocrData.birthday) {
				// 将生日格式从"1992年8月18日"转换为"1992-08-18"
				const birthdayMatch = ocrData.birthday.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/)
				if (birthdayMatch) {
					const year = birthdayMatch[1]
					const month = birthdayMatch[2].padStart(2, '0')
					const day = birthdayMatch[3].padStart(2, '0')
					registerForm.value.birthday = `${year}-${month}-${day}`
				}
			}

			if (ocrData.cardAddress) {
				registerForm.value.address = ocrData.cardAddress
			}

			if (ocrData.authority) {
				registerForm.value.authority = ocrData.authority
			}

			if (ocrData.cardExpStart) {
				registerForm.value.cardExpStart = ocrData.cardExpStart.replaceAll('.', '-')
			}

			if (ocrData.cardExpEnd) {
				registerForm.value.cardExpEnd = ocrData.cardExpEnd.replaceAll('.', '-')
			}

			ElMessage.success('身份证信息识别成功，请核对填写的信息')
		} else {
			ElMessage.warning('身份证识别失败，请检查图片质量或手动填写信息')
		}
	} catch (error) {
		console.error('OCR识别失败:', error)
		ElMessage.error('身份证识别失败，请重新上传或手动填写信息')
	} finally {
		ocrProcessing.value = false
	}
}

/**
 * 处理文件上传成功（新版本，使用原始File对象）
 * @param data 上传成功的文件数据
 */
const handleFileUploaded = (data: { fileId: number; file: File }[]) => {
	console.log('文件上传成功（新事件）:', data)
	if (data.length > 0) {
		// 对第一个上传的文件进行OCR识别
		handleIdCardOcr(data[0].file)
	}
}

const checkUserStatus = () => {
	if (curAthlete) {
		registerForm.value = {
			...curAthlete,
			registerYear: String(curAthlete.registerYear)
		}

		// 需要年度确认
		if (curAthlete.yearId) setYearlyConfirmMode(true)
		else {
			// 不需要年度确认，默认勾选协议
			agreementChecked.info = true
			agreementChecked.privacy = true
		}
	}
}

// 初始化
onMounted(async () => {
	// 检查用户状态，判断是否需要年度确认 和 是否 已经提交注册
	checkUserStatus()
	console.log('registerForm.value:', registerForm.value)
})
</script>

<template>
	<div class="athlete-register-page">
		<!-- 标题 -->
		<div class="bg-primary flex flex-col items-center justify-center pt-5">
			<div class="text-2xl text-primary font-500 mb-3">{{ isYearlyConfirm ? '运动员年度确认' : '运动员注册申请' }}</div>
			<div class="text-sm text-foreground-tertiary">
				{{ isYearlyConfirm ? '仅可修改标记✓的字段，其他信息保持不变' : '请按步骤完整填写信息，确保信息真实有效' }}
			</div>
		</div>
		<!-- 步骤导航 -->
		<StepNavigation
			:current-step="currentStep"
			:steps="steps"
		/>

		<!-- 证件审核记录资料 -->
		<div
			v-if="isSubmit"
			class="p-5 bg-primary rounded mb-4"
		>
			<div class="text-base text-primary font-500 mb-4">证件审核记录资料</div>
			<div class="flex flex-col gap-6">
				<div
					v-for="record in auditRecords"
					:key="record.id"
					class="relative"
				>
					<!-- 时间线 -->
					<div class="flex gap-4">
						<!-- 左侧图标和线 -->
						<div class="flex flex-col items-center">
							<img
								:src="fileIcon"
								class="size-6 object-fill"
							/>
							<div class="w-px bg-light flex-1 mt-2" />
						</div>
						<!-- 右侧内容 -->
						<div class="flex-1 pb-2">
							<div class="flex items-center justify-between mb-2">
								<div class="text-primary font-500">{{ record.title }}</div>
								<div class="text-secondary text-sm">{{ record.time }}</div>
							</div>
							<div class="text-secondary text-sm mb-0.5">操作人：{{ record.operator }}</div>
							<div class="text-secondary text-sm">{{ record.description }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div
			class="mx-auto bg-primary"
			:class="[disabled ? 'pointer-events-none' : '']"
		>
			<!-- 表单内容区 -->
			<div class="mx-auto w-[866px] p-6 min-h-[800px]">
				<!-- 年度确认时的特殊说明 -->
				<div
					v-if="isYearlyConfirm"
					class="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg"
				>
					<div class="flex items-start gap-3">
						<el-icon class="text-blue-500 mt-0.5">
							<InfoFilled />
						</el-icon>
						<div class="text-sm text-blue-700">
							<div class="font-medium mb-2">年度确认说明：</div>
							<div class="space-y-1">
								<div>• 身份证、照片等资质材料在年度确认时不可修改</div>
								<div>• 如有新的资质证书或证明材料，请在提交时上传</div>
								<div>• 系统将使用上次注册时的资质材料信息</div>
							</div>
						</div>
					</div>
				</div>

				<!-- 基本信息步骤 -->
				<div class="step-content">
					<h3 class="text-primary text-lg font-semibold mb-6">基本信息</h3>
					<!-- 身份证照片上传区（独立组件） -->
					<div>
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								身份证正反面照片
								<span class="text-foreground-tertiary text-xs ml-2"> 上传后将自动识别身份信息并填入表单 </span>
							</label>
						</div>
						<!-- 上传区域容器 -->
						<div class="flex gap-6">
							<!-- 身份证正面上传 -->
							<div class="flex-1">
								<CommonUpload
									v-model="registerForm.identityFront"
									:disabled="isSubmit || isYearlyConfirm"
									:placeholder-src="idFrontPlaceholder"
									width="312px"
									height="198px"
									@fileUploaded="handleFileUploaded"
								/>
							</div>

							<!-- 身份证背面上传 -->
							<div class="flex-1">
								<CommonUpload
									v-model="registerForm.identityBack"
									:disabled="isSubmit || isYearlyConfirm"
									:placeholder-src="idBackPlaceholder"
									width="312px"
									height="198px"
									@fileUploaded="handleFileUploaded"
								/>
							</div>
						</div>
					</div>

					<!-- QForm 表单区域 -->
					<QForm
						ref="basicFormRef"
						:model="registerForm"
						:disabled="disabled"
						:form-options="basicFormOptions"
						:label-position="'top'"
						:col="12"
						:gutter="36"
						label-width="120px"
					/>
				</div>

				<!-- 资质信息步骤 -->
				<div class="step-content">
					<h3 class="text-primary text-lg font-semibold mb-6">资质信息</h3>
					<!-- 近期免冠照片上传 -->
					<div class="mb-8">
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								上传近期免冠照片
								<span class="text-foreground-tertiary text-xs ml-2"> 用于人脸识别验证，要求正面、清晰 </span>
							</label>
						</div>
						<CommonUpload
							v-model="registerForm.personPhoto"
							:disabled="isSubmit || isYearlyConfirm"
							:placeholder-src="mgzPlaceholder"
							width="136px"
							height="182px"
						/>
					</div>

					<!-- 资质证书上传 -->
					<div class="mb-8">
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								运动员资质证书
								<span class="text-foreground-tertiary text-xs ml-2"> 最多可上传3张，要求正面、清晰 </span>
							</label>
						</div>

						<CommonUpload
							v-model="registerForm.qualifications"
							:disabled="isSubmit || isYearlyConfirm"
							:placeholder-src="certiPlaceholder"
							:max-count="3"
							is-array
							width="155px"
							height="116px"
						/>
					</div>

					<!-- 其他证明材料上传 -->
					<div class="mb-8">
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								其他相关证明
								<span class="text-foreground-tertiary text-xs ml-2"> 最多可上传9张，如体检报告、学籍证明等 </span>
							</label>
						</div>
						<div class="w-[600px]">
							<CommonUpload
								v-model="registerForm.otherMaterial"
								:disabled="isSubmit"
								:placeholder-src="otherPlaceholder"
								:max-count="9"
								is-array
								width="155px"
								height="116px"
							/>
						</div>
					</div>
				</div>

				<!-- 身份验证步骤 -->
				<div class="step-content">
					<h3 class="text-primary text-lg font-semibold mb-6">身份验证</h3>

					<!-- 认证操作区域 -->
					<div class="bg-white rounded-lg flex flex-col gap-4 space-y-0">
						<div
							v-for="item in authList"
							:key="item.title"
							class="flex items-center rounded justify-between px-4 py-5 border border-background-tertiary hover:shadow-[0px_2px_5px_0px_rgba(0,0,0,0.1)] transition-all duration-300"
						>
							<!-- 左侧图标和信息 -->
							<div class="flex gap-4">
								<img
									:src="item.img"
									class="size-[30px] item-start"
									alt=""
								/>
								<div class="flex-1">
									<h4 class="text-gray-900 font-medium text-base mb-1">
										{{ item.title }}
									</h4>
									<p class="text-gray-500 text-sm">
										{{ item.description }}
									</p>
								</div>
							</div>

							<!-- 右侧操作按钮 -->
							<div class="flex items-center">
								<!-- 未验证状态 -->
								<el-button
									v-if="item.validateStatus === 0"
									size="default"
									plain
									:loading="validating"
									class="px-6 py-2"
									@click="handleVerify(item.type)"
								>
									{{ item.unValidate }}
								</el-button>

								<!-- 已验证状态 -->
								<div
									v-else
									class="flex items-center gap-2 px-4 py-2 bg-green-50 text-green-600 rounded-md border border-green-200"
								>
									<svg
										class="w-4 h-4"
										fill="currentColor"
										viewBox="0 0 20 20"
									>
										<path
											fill-rule="evenodd"
											d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
											clip-rule="evenodd"
										/>
									</svg>
									<span class="text-sm font-medium">
										{{ item.validated }}
									</span>
								</div>
							</div>
						</div>
					</div>

					<!-- 申请确认 -->
					<div class="bg-background-secondary border rounded p-4 mt-6">
						<h4 class="text-primary text-base font-medium mb-4">申请确认</h4>
						<div class="space-y-1">
							<el-checkbox
								v-model="agreementChecked.info"
								class="confirm"
								label="我确认以上填写的所有信息真实有效，如有虚假信息愿承担相应责任"
							/>
							<el-checkbox
								v-model="agreementChecked.privacy"
								class="confirm"
								label="我同意将个人信息用于运动员注册管理，并接受相关公示要求"
							/>
						</div>
					</div>
				</div>

				<!-- 分割线 -->
				<div class="h-[1px] bg-background-tertiary my-6" />

				<!-- 底部操作按钮 -->
				<div class="flex justify-end">
					<el-button
						type="primary"
						size="large"
						:loading="submitting"
						:disabled="!canSubmit || disabled"
						@click="handleSubmit"
					>
						{{ isYearlyConfirm ? '提交申请' : '提交确认' }}
					</el-button>
				</div>
			</div>
		</div>
		<!-- 结束正常内容 div -->

		<!--  确认提交弹窗 -->
		<SubmitConfirmDialog
			v-model="showConfirmDialog"
			:loading="submitting"
			@confirm="handleConfirmSubmit"
			@cancel="handleCancelSubmit"
		/>
	</div>
</template>

<style lang="scss" scoped>
.step-content {
	animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
</style>
